package com.adee.netty.demo;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;

public class NettyServerHandler2 extends ChannelInboundHandlerAdapter {
    // 自定义业务线程池，用于在handler中异步处理耗时业务
    private final EventExecutorGroup group = new DefaultEventExecutorGroup(16);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 真正的异步执行任务
        group.execute(() -> {
            try {
                System.out.println("channelRead task1..." + Thread.currentThread().getName());
                Thread.sleep(3000);
                ctx.channel().writeAndFlush(msg + "1");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        group.execute(() -> {
            try {
                System.out.println("channelRead task2..." + Thread.currentThread().getName());
                Thread.sleep(4000);
                ctx.channel().writeAndFlush(msg + "2");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        group.execute(() -> {
            try {
                System.out.println("channelRead task3..." + Thread.currentThread().getName());
                Thread.sleep(5000);
                ctx.channel().writeAndFlush(msg + "3");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(cause.getMessage());
        ctx.close();
    }
}
